//
//  HomeViewController.m
//  CloudWeibo
//
//  Created by CLOUD on 11/14/14.
//  Copyright (c) 2014 Cloud. All rights reserved.
//

#import "HomeViewController.h"
#import "WeiBoModel.h"
#import "UIFactory.h"
#import "WeiBoTableView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MainViewController.h"
#import "DetailViewController.h"
#import "CLOUDAppDelegate.h"


@interface HomeViewController ()

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"微博";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"绑定账号" style:UIBarButtonItemStyleBordered target:self action:@selector(bindAction:)];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"注消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelAction:)];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationItem.leftBarButtonItem = leftItem;
    
    _tableView = [[WeiBoTableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-20-49-44) style:UITableViewStylePlain];
    _tableView.eventDelegate = self;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    if (self.sinaweibo.isAuthValid) {
        [self loadWeiboData];
    }else{
        [self.sinaweibo logIn];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.appDelegate.menuViewController setEnableGesture:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.appDelegate.menuViewController setEnableGesture:NO];
}

- (void) loadWeiboData
{
    [super showLoading: YES];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"20" forKey:@"count"];
    [self.sinaweibo requestWithURL:@"statuses/home_timeline.json" params:params httpMethod:@"GET" delegate:self];
}

- (void) pullDownData
{
        if (self.topWeiBoId.length == 0) {
        NSLog(@"topWeiBoId为空");
        return;
    }
     
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"20", @"count",self.topWeiBoId, @"since_id", nil];

    [self.sinaweibo requestWithURL:@"statuses/home_timeline.json" params:params httpMethod:@"GET" block:^(id result){
        [self pullDownDataFinish:result];
    }];
}


- (void) pullUpData
{
    if (self.bottomWeiBoId.length == 0) {
        NSLog(@"bottomWeiBoId为空");
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"20", @"count",self.bottomWeiBoId, @"max_id", nil];
    
    [self.sinaweibo requestWithURL:@"statuses/home_timeline.json" params:params httpMethod:@"GET" block:^(id result){
        [self pullUpDataFinish:result];
    }];
}
     
- (void) pullDownDataFinish:(id)result {
    NSArray  *statuses = [result  objectForKey:@"statuses"];
    NSMutableArray *weiBos = [NSMutableArray arrayWithCapacity:[statuses count]];
    for (NSDictionary *statusDic in statuses) {
        WeiBoModel *weiBo = [[WeiBoModel alloc] initWithDataDic:statusDic];
        [weiBos addObject:weiBo];
        [weiBo release];
    }
    
    if (weiBos.count > 0) {
        WeiBoModel *firstWeiBo = [weiBos objectAtIndex:0];
        self.topWeiBoId = [firstWeiBo.weiBoId stringValue];
    }
    
    [weiBos addObjectsFromArray:self.weiBos];
    self.weiBos = weiBos;
    self.tableView.data = weiBos;
    
    [self.tableView reloadData];
    
    [self.tableView doneLoadingTableViewData];
    
    //NSLog(@"下拉更新条数%d", [statuses count]);
    [self showNewWeiBoCount:[statuses count]];
    
    
}


- (void) pullUpDataFinish:(id)result {
    NSArray  *statuses = [result  objectForKey:@"statuses"];
    NSMutableArray *weiBos = [NSMutableArray arrayWithCapacity:[statuses count]];
    for (NSDictionary *statusDic in statuses) {
        WeiBoModel *weiBo = [[WeiBoModel alloc] initWithDataDic:statusDic];
        [weiBos addObject:weiBo];
        [weiBo release];
    }
    
    if (weiBos.count > 0) {
        WeiBoModel *bottomWeiBo = [weiBos lastObject];
        self.bottomWeiBoId = [bottomWeiBo.weiBoId stringValue];
        [weiBos removeObjectAtIndex:0];
    }
    
    if (statuses.count >= 20) {
        self.tableView.isMore = YES;
    }else {
        self.tableView.isMore = NO;
    }
    
    
    [self.weiBos addObjectsFromArray:weiBos];
    self.tableView.data = self.weiBos;
    
    [self.tableView reloadData];
    [self.tableView stopPullup];
    
}

- (void) showNewWeiBoCount:(int) count
{
    if (count > 0) {
        if (newStatus == nil) {
            newStatus = [[UIFactory createImageView:@"timeline_new_status_background.png"] retain];
            UIImage *image = [newStatus.image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
            newStatus.frame = CGRectMake(5, -40, ScreenWidth - 10, 40);
            newStatus.image = image;
            newStatus.topCapHeight = 5;
            newStatus.leftCapWidth = 5;
            [self.view addSubview:newStatus];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
            label.tag = 20002;
            label.font = [UIFont systemFontOfSize:16.0f];
            label.textColor = [UIColor blackColor];
            label.backgroundColor = [UIColor clearColor];
            label.text = [NSString stringWithFormat:@"%d条新微博", count];
            [newStatus addSubview:label];
            [label release];
            

        }
        
        UILabel *label = (UILabel *) [newStatus viewWithTag:20002];
        [label sizeToFit];
        label.origin = CGPointMake((newStatus.width-label.width)/2, (newStatus.height-label.height)/2);
        label.text = [NSString stringWithFormat:@"%d条新微博", count];
        [UIView animateWithDuration:0.6 animations:^{
            newStatus.top = 5;
        } completion:^(BOOL finish){
            if (finish) {
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDelay:1];
                [UIView setAnimationDuration:0.6];
                [UIView commitAnimations];
                newStatus.top = -40;
            }
        }];
        
        
        NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"msgcome" ofType:@"wav"];
        NSURL *url = [NSURL fileURLWithPath:musicPath];
        SystemSoundID soundId;
        AudioServicesCreateSystemSoundID((CFURLRef)url, &soundId);
        AudioServicesPlayAlertSound(soundId);
        
    }
    
    MainViewController *main =  (MainViewController *)self.tabBarController;
    [main showBadge:NO];
}


- (void)refreshWeiBo
{
    [self.tableView refreshData];
    [self pullDownData];
}


- (void) pullDown:(BaseTableView *) tableView
{
    NSLog(@"加载数据");
    [self pullDownData];
    //[tableView performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3];
}

- (void) pullUp:(BaseTableView *)tableView
{
    [self pullUpData];
    NSLog(@"上拉加载");
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)bindAction:(UIBarButtonItem *) buttonItem
{
    [self.sinaweibo logIn];
}

- (void)cancelAction:(UIBarButtonItem *) buttonItem
{
    [self.sinaweibo logOut];
}


- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError");
}
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    [super showLoading:NO];
    self.tableView.hidden = NO;
    //NSLog(@"%@", result);
    NSArray  *statuses = [result  objectForKey:@"statuses"];
    NSMutableArray *weiBos = [NSMutableArray arrayWithCapacity:[statuses count]];
    self.weiBos = weiBos;
    for (NSDictionary *statusDic in statuses) {
        WeiBoModel *weiBo = [[WeiBoModel alloc] initWithDataDic:statusDic];
        [weiBos addObject:weiBo];
        [weiBo release];
    }
    
    if (statuses.count >= 20) {
        self.tableView.isMore = YES;
    }else {
        self.tableView.isMore = NO;
    }
    
    
    if (weiBos.count > 0) {
        WeiBoModel *weiBo = [weiBos objectAtIndex:0];
        self.topWeiBoId = [weiBo.weiBoId stringValue];
        WeiBoModel *bottomWeiBo = [weiBos lastObject];
        self.bottomWeiBoId = [bottomWeiBo.weiBoId stringValue];
    }
    
    //NSLog(@"=================%@",weiBos);
    self.tableView.data = weiBos;
    [self.tableView reloadData];
}

- (void)dealloc {
    [_tableView release];
    [super dealloc];
}
@end
